﻿using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace Nvigorate.Test.Comparer
{
    public class DataSetEqualityComparer : IEqualityComparer<DataSet>
    {
        private readonly DataTableEqualityComparer _tableComparer = new DataTableEqualityComparer();

        public bool Equals(DataSet x, DataSet y)
        {
            if (ReferenceEquals(x, y)) return true;
            if (x == null || y == null) return false;

            if (!x.DataSetName.Equals(y.DataSetName)) return false;
            if (x.Tables.Count != y.Tables.Count) return false;

            foreach (DataTable table in x.Tables)
            {
                if (!y.Tables.Cast<DataTable>().Contains(table, _tableComparer)) return false;
            }

            return true;
        }

        public int GetHashCode(DataSet obj)
        {
            if (obj == null) return 0;
            int hash = obj.DataSetName.GetHashCode();
            foreach (DataTable table in obj.Tables)
            {
                hash += table == null ? 0 : 29*_tableComparer.GetHashCode(table);
            }
            return hash;
        }
    }
}